# myadmin/views.py 中定义如下视图
import os
import json
import time
import oss2
import uuid
import shutil
# import pandas
import datetime
import requests
from django.shortcuts import render
from django.views import View
from django.db.transaction import atomic
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth import authenticate, login
from django.contrib.auth.models import User
from django.contrib.sessions.models import Session
from libs.utils.ajax import ajax_ok, ajax_fail
from django.contrib.auth.hashers import make_password
from libs.utils.com_func import Struct
from cms.settings import IMAGES_LINK
from django.core.paginator import Paginator
from myadmin.common.common import down_load_image, remove_image, Bytesio_image, \
    upload_oss_file, down_search_video, media_audio, del_file_one, del_file_all, del_search_video, down_ubuntu_video

from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login, get_user_model
User = get_user_model()

@csrf_exempt
@atomic()
def registerAction(request):
    """
    接口功能说明：注册和修改密码（督导账号注册）
    --------------------------------------------
    接口逻辑说明：注册和修改密码（督导账号注册）
    --------------------------------------------
    修改人        修改时间        修改原因
    --------------------------------------------
    张凯           2020-9-22	   创建
    --------------------------------------------
    """
    """
    @api {post} /admin/regist/  1 注册和修改密码（督导账号注册）
    @apiGroup user
    @apiName registerAction

    @apiParam     {Int}        rank                     督导级别 1 一级督导 2二级督导 3 管理员
    @apiParam     {String}     username                 工号
    @apiParam     {String}     password                 密码
    @apiParam     {String}     supervisor_name          督导老师名称
    @apiExample {Array} 获取数据
    获取值类型:JSON
    {
        "username":"zd12356",
        "password":"zd12356",
        "supervisor_name":"王督导",
        "rank":3
    }

    返回值类型: JSON
    {
        "response": "ok",
        "data": "",
        "error": "",
        "message": ""
    }
    """
    post = json.loads(request.body, strict=False)
    username = post.get('username', '').lower()
    password = post.get('password')
    supervisor_name = post.get('supervisor_name', "")  # 督导名称
    rank = int(post.get('rank', 1))  # 级别    1 以及督导  2 二级督导  3 管理员
    is_change = int(post.get('is_change', 1))  # 是否是修改密码 1 修改密码 2新用户注册
    person = User.objects.filter(username=username).last()
    if person:
        if is_change == 2:
            return ajax_fail(message="用户已经存在")
        first_pass = person.password.split('$')
        hasher = first_pass[0]
        salt = first_pass[1]  # grabbing salt from the first password of the database
        newpassword = make_password(password, salt, hasher)
        person.password = newpassword
        person.rank = rank
        person.save()
        return ajax_fail(message="密码修改成功！")
    user = User.objects.create_user(username, '', password)
    user.supervisor_name = supervisor_name
    user.rank = rank
    user.save()
    return ajax_ok()


@csrf_exempt
@atomic()
def user_list(request):
    """
    接口功能说明：用户列表
    --------------------------------------------
    接口逻辑说明：用户列表
    --------------------------------------------
    修改人        修改时间        修改原因
    --------------------------------------------
    张凯           2020-9-22	   创建
    --------------------------------------------
    """
    """
    @api {post} /admin/user/list/?user_id=1  2 用户列表（督导用户列表）
    @apiGroup user
    @apiName user_list

   @apiParam     {Int}           user_id              管理员ID
   @apiParam     {String}        supervisor_name      督导老师姓名
   @apiParam     {Int}           page                 页码
    @apiExample {Array} 获取数据
    获取值类型:JSON
    {
        "supervisor_name":"王督导",
        "page":1,
    }
    
    @apiSuccess {List}     user_list              用户列表
    @apiSuccess {String}   user_list.supervisor_name    姓名
    @apiSuccess {String}   user_list.password           密码
    @apiSuccess {String}   user_list.username           账号
    @apiSuccess {String}   user_list.rank               级别 1 一级督导 2 二级督导
    @apiSuccess {String}   user_list.add_time           创建时间
    @apiSuccessExample {Array} 返回数据
    返回值类型: JSON
    {
        "data":{
            "username":"zd12356",
            "supervisor_name":"王督导",
            "password":"密码",
            "rank":1,
            "add_time":"2020-12-12 14:20:50"
        },
        "response": "ok",
        "data": "",
        "error": "",
        "message": ""
    }
    """
    post = json.loads(request.body, strict=False)

    supervisor_name = post.get('supervisor_name', "")  # 督导名称
    page = post.get('page')                           # 页码

    if supervisor_name:
        Users = User.objects.filter(supervisor_name__icontains=supervisor_name, is_active=1).values("id", "supervisor_name", "username", "password", "rank", "date_joined").order_by("-id")

    else:
        Users = User.objects.filter(supervisor_name__icontains=supervisor_name, is_active=1).values("id", "supervisor_name",
                                                                                       "username", "password", "rank", "date_joined").order_by("-id")

    data = Struct()
    if Users:
        paginator = Paginator(Users, 10)  # 实例化分页对象，每页展示10条记录
        total_page = paginator.num_pages  # 总页数
        try:
            Users = paginator.page(page).object_list  # 获取某页对应的记录
        except PageNotAnInteger:
            page = 1
            Users = paginator.page(page).object_list  # 如果页面不是整数，取第一页的记录
        except EmptyPage:
            page = paginator.num_pages
            Users = paginator.page(paginator.num_pages).object_list  # 如果页码太大，取最后一页记录
        user_list = []
        num = 1
        for obj in Users:
            try:
                row = Struct()
                row.num = num  # 序号
                row.article_id = obj.get("id")  # 文章id
                row.supervisor_name = obj.get("supervisor_name", '')  # 督导老师姓名
                row.username = obj.get("username")          # 用户名
                row.password = obj.get("password")          # 密码
                row.rank = obj.get("rank")                  # 级别
                row.data_joined = str(obj.get("date_joined")).split('.')[0]    # 创建时间
                user_list.append(row)
                num +=1
            except:
                continue
    else:
        user_list = []
        total_page = 0
        page = 0
    data.article_list = user_list  # 文章列表
    data.total_page = total_page  # 总页码
    data.current_page = page  # 页码
    return ajax_ok(data)


@csrf_exempt
@atomic()
def delete_user(request):
    """
    接口功能说明：删除督导用户
    --------------------------------------------
    接口逻辑说明：删除督导用户
    --------------------------------------------
    修改人        修改时间        修改原因
    --------------------------------------------
    张凯           2020-9-22	   创建
    --------------------------------------------
    """
    """
    @api {post} /admin/delete/user/?user_id=1  3 删除督导用户（删除督导用户）
    @apiGroup user
    @apiName delete_user

    @apiParam     {Int}           user_id              管理员ID
    @apiParam     {String}        admin_user_id        督导老师用户id
    @apiExample {Array} 获取数据
    获取值类型:JSON
    {
        "admin_user_id":12,
    }
    @apiSuccessExample {Array} 返回数据
    返回值类型: JSON
    {
        "response": "ok",
        "data": "",
        "error": "",
        "message": ""
    }
    """
    post = json.loads(request.body, strict=False)
    admin_user_id = post.get('admin_user_id', 0)  # 督导老师id
    admin_user = User.objects.filter(id=admin_user_id).last()
    if admin_user:  # 删除

        try:
            User.objects.filter(username=admin_user.username).delete()
            # admin_user.update
            # uuid_name = uuid.uuid1()
            # admin_user.update(**{"is_staff": 1, "username":uuid_name})
        #
        except:
            return ajax_fail(message="删除数据不存在")
    else:
        return ajax_fail(message="删除数据不存在")
    return ajax_ok()


@csrf_exempt
@atomic()
def management_ogin(request):
    """
        接口功能说明：管理后台登录
        --------------------------------------------
        接口逻辑说明：管理后台登录
        --------------------------------------------
        修改人        修改时间        修改原因
        --------------------------------------------
        张凯           2020-9-22	   创建
        --------------------------------------------
        """
    """
    @api {post} /admin/management/login/  4 管理后台登录（管理后台登录）
    @apiGroup user
    @apiName Login

    @apiParam     {String}     username                 管理后台账号
    @apiParam     {String}     password                 管理后台密码
    @apiExample {Array} 获取数据
    获取值类型:JSON
    {
        "username":"zd12356",
        "password":"zd12356",
    }

    @apiSuccess {Int}     rank                          督导级别 1 一级督导 2二级督导 3 管理员
    @apiSuccessExample {Array} 返回数据
    返回值类型: JSON
    {
        "response": "ok",
        "data":{
            "user_id"：1,
            "supervisor_name"："管理后台用户名",
            "sessionid"："督导老师姓名",
        },
        "error": "",
        "message": ""
    }
    """
    post = json.loads(request.body.decode('utf-8'), strict=False)
    username = post.get('username', '').lower()
    password = post.get('password', '')
    if not username or not password:
        print("未输入账号或密码")
    user = authenticate(username=username, password=password)  # 验证用户
    if not user:
        return ajax_fail(message=u"账号或密码错误！")
    if user.is_active != 2:
        return ajax_fail(message=u"账号或密码错误")
    login(request, user)
    # 设置session过期时间
    expiry_time = (datetime.datetime.combine(datetime.date.today(),
                                             datetime.time.max) - datetime.datetime.now()).seconds  # 今天的结束时间减去当前时间
    request.session.set_expiry(expiry_time)  # 设置过期时间为晚上12点过期
    data = {}
    data['user_id'] = int(user.id)
    data['supervisor_name'] = user.supervisor_name  # 督导老师姓名
    data["sessionid"] = request.session.session_key
    return ajax_ok(data)


@csrf_exempt
@atomic()
def applet_login(request):
    """
        接口功能说明：小程序登录
        --------------------------------------------
        接口逻辑说明：小程序登录
        --------------------------------------------
        修改人        修改时间        修改原因
        --------------------------------------------
        张凯           2020-9-22	   创建
        --------------------------------------------
        """
    """
    @api {post} /admin/applet/login/  5 小程序登录（小程序登录）
    @apiGroup user
    @apiName applet_login

    @apiParam     {String}     username                 工号
    @apiParam     {String}     password                 密码
    @apiExample {Array} 获取数据
    获取值类型:JSON
    {
        "username":"zd12356",
        "password":"zd12356",
    }

    @apiSuccess {Int}     rank                          督导级别 1 一级督导 2二级督导 3 管理员
    @apiSuccessExample {Array} 返回数据
    返回值类型: JSON
    {
        "response": "ok",
        "data":{
            "user_id"：1,
            "supervisor_name"："督导老师姓名",
            "sessionid"："",
            "rank"：1,
        },
        "error": "",
        "message": ""
    }
    """
    post = json.loads(request.body.decode('utf-8'), strict=False)
    username = post.get('username', '').lower()
    password = post.get('password', '')
    print(username, password)
    if not username or not password:
        print("未输入账号或密码")
    user = authenticate(username=username, password=password)  # 验证用户
    if not user:
        print(22222,user)
        return ajax_fail(message=u"账号或密码错误！")
    login(request, user)
    # 设置session过期时间
    expiry_time = (datetime.datetime.combine(datetime.date.today(),
                                             datetime.time.max) - datetime.datetime.now()).seconds  # 今天的结束时间减去当前时间
    request.session.set_expiry(expiry_time)  # 设置过期时间为晚上12点过期
    data = {}
    data['user_id'] = int(user.id)
    data['supervisor_name'] = user.supervisor_name  # 督导老师姓名
    data['rank'] = int(user.rank)                   # 督导级别 1 一级督导 2二级督导 3 管理员
    data["sessionid"] = request.session.session_key
    return ajax_ok(data)

# 退出登录
def out_login(request):
    """
            接口功能说明：退出登录
            --------------------------------------------
            接口逻辑说明：退出登录
            --------------------------------------------
            修改人        修改时间        修改原因
            --------------------------------------------
            张凯           2020-9-22	   创建
            --------------------------------------------
            """
    """
    @api {get} /admin/login/?sessionid="222"  6 退出登录
    @apiGroup user
    @apiName out_login
    @apiParam   {Int}     sessionid                          sessionid
    
    @apiSuccessExample {Array} 返回数据
    返回值类型: JSON
    {
        "response": "ok",
        "data": "",
        "error": "",
        "message": ""
    }
    """
    sessionid = request.GET.get('sessionid')
    session = Session.objects.filter(session_key=sessionid).last()
    session.delete()
    return ajax_ok()

# 下载生成视频excel
@csrf_exempt
@atomic()
def down_video_excel(request):
    sraerch_video_list = [
        {
            "main_sum_time": "1:1:15",
            "cover_sum_time": "0:58:28",
            "main_name": "http://turingcom.oss-cn-hangzhou.aliyuncs.com/py_search_video/05770686-f32d-11ea-8b3e-1831bf0bc56e_1599718527.mp4",
            "cover_name": "https://turingcom.oss-cn-hangzhou.aliyuncs.com/py_search_video/6463b01e-f32d-11ea-a60e-1831bf0bc56e_1599718687.mp4",
            "frame_info": [
                {
                    "main_time": "00:15:56",
                    "cover_time": "00:16:28",
                    "main_path": "https://turingcom.oss-cn-hangzhou.aliyuncs.com/py_image_search/9cfea580-f3f3-11ea-beaa-5cea1d2223b6_1599803822.jpg",
                    "cover_path": "https://turingcom.oss-cn-hangzhou.aliyuncs.com/py_image_search/9d1f3680-f3f3-11ea-be13-5cea1d2223b6_1599803822.jpg"
                },
                {
                    "main_time": "00:36:06",
                    "cover_time": "00:36:53",
                    "main_path": "https://turingcom.oss-cn-hangzhou.aliyuncs.com/py_image_search/9d340fd8-f3f3-11ea-a4d7-5cea1d2223b6_1599803822.jpg",
                    "cover_path": "https://turingcom.oss-cn-hangzhou.aliyuncs.com/py_image_search/9d540514-f3f3-11ea-afed-5cea1d2223b6_1599803823.jpg"
                },
                {
                    "main_time": "00:57:01",
                    "cover_time": "00:56:50",
                    "main_path": "https://turingcom.oss-cn-hangzhou.aliyuncs.com/py_image_search/9d73ac78-f3f3-11ea-b6e7-5cea1d2223b6_1599803823.jpg",
                    "cover_path": "https://turingcom.oss-cn-hangzhou.aliyuncs.com/py_image_search/9d8837cc-f3f3-11ea-9a45-5cea1d2223b6_1599803823.jpg"
                }
            ]
        },
        {
            "main_sum_time": "1:1:15",
            "cover_sum_time": "0:59:34",
            "main_name": "http://turingcom.oss-cn-hangzhou.aliyuncs.com/py_search_video/05770686-f32d-11ea-8b3e-1831bf0bc56e_1599718527.mp4",
            "cover_name": "https://turingcom.oss-cn-hangzhou.aliyuncs.com/py_search_video/c176105e-f32d-11ea-9a5f-1831bf0bc56e_1599718843.mp4",
            "frame_info": [
                {
                    "main_time": "00:15:19",
                    "cover_time": "00:14:18",
                    "main_path": "https://turingcom.oss-cn-hangzhou.aliyuncs.com/py_image_search/9e0fcfa4-f3f3-11ea-a994-5cea1d2223b6_1599803824.jpg",
                    "cover_path": "https://turingcom.oss-cn-hangzhou.aliyuncs.com/py_image_search/9e30fc88-f3f3-11ea-92a5-5cea1d2223b6_1599803824.jpg"
                },
                {
                    "main_time": "00:24:09",
                    "cover_time": "00:25:33",
                    "main_path": "https://turingcom.oss-cn-hangzhou.aliyuncs.com/py_image_search/9e4c3a12-f3f3-11ea-9a03-5cea1d2223b6_1599803824.jpg",
                    "cover_path": "https://turingcom.oss-cn-hangzhou.aliyuncs.com/py_image_search/9e6a34d2-f3f3-11ea-9c58-5cea1d2223b6_1599803824.jpg"
                },
                {
                    "main_time": "00:53:16",
                    "cover_time": "00:53:23",
                    "main_path": "https://turingcom.oss-cn-hangzhou.aliyuncs.com/py_image_search/9e84af92-f3f3-11ea-8edd-5cea1d2223b6_1599803825.jpg",
                    "cover_path": "https://turingcom.oss-cn-hangzhou.aliyuncs.com/py_image_search/9ea42fee-f3f3-11ea-ba28-5cea1d2223b6_1599803825.jpg"
                }
            ]
        }
    ]

    # 创建工作簿
    workbook = xlsxwriter.Workbook("羊毛衫.xlsx",
                                   options={  # 全局设置
                                       'strings_to_numbers': True,  # str 类型数字转换为 int 数字
                                       'strings_to_urls': False,  # 自动识别超链接
                                       'constant_memory': False,  # 连续内存模式 (True 适用于大数据量输出)
                                       'default_format_properties': {
                                           'font_name': '微软雅黑',  # 字体. 默认值 "Arial"
                                           'font_size': 10,  # 字号. 默认值 11
                                           'bold': False,  # 字体加粗
                                           'border': 1,  # 单元格边框宽度. 默认值 0
                                           'align': 'vcenter',  # 对齐方式
                                           'valign': 'vcenter',  # 垂直对齐方式
                                           # 'text_wrap': False,  # 单元格内是否自动换行
                                           # ...
                                       },
                                   }
                                   )
    # 创建工作表
    worksheet = workbook.add_worksheet('first_sheet')
    # 写单元格
    worksheet.write_row(0, 0, ['正版视频长度', '正版视频URL', '盗版视频长度', '盗版视频URL', '正版图片抽取时间', '正版图片', '盗版图片抽取时间', '盗版图片'])
    worksheet.set_column('A:C', 10)  # 列宽约等于8像素 行高约等于1.37像素
    worksheet.set_column('B:C', 30)
    worksheet.set_column('D:E', 30)
    worksheet.set_column('F:G', 30)
    worksheet.set_column('H:I', 30)
    i = 1
    excel_row = 1
    for obj in sraerch_video_list:
        main_sum_time = obj.get('main_sum_time')
        cover_sum_time = obj.get('cover_sum_time')
        main_name = obj.get('main_name')
        cover_name = obj.get('cover_name')
        frame_info = obj.get('frame_info')
        for x in frame_info:
            worksheet.write(excel_row, 0, main_sum_time)
            worksheet.write(excel_row, 1, main_name)
            worksheet.write(excel_row, 2, cover_sum_time)
            worksheet.write(excel_row, 3, cover_name)
            main_time = x.get('main_time')
            cover_time = x.get('cover_time')
            main_path = x.get('main_path')
            cover_path = x.get('cover_path')

            worksheet.write(excel_row, 4, main_time)
            # 以文件流的方式上传（第一种方法）
            Bytesio_image(main_path, worksheet, excel_row, 5)
            worksheet.set_row(excel_row, 80)
            worksheet.write(excel_row, 6, cover_time)
            # 以文件流的方式上传（第一种方法）
            Bytesio_image(cover_path, worksheet, excel_row, 7)
            excel_row += 1
        if i == 1:
            worksheet.merge_range('A2:A'+str(excel_row), main_sum_time)
            worksheet.merge_range('B2:B'+str(excel_row), main_name)
            worksheet.merge_range('C2:C' + str(excel_row), cover_sum_time)
            worksheet.merge_range('D2:D' + str(excel_row), cover_name)
        else:
            start_len = excel_row - len(frame_info)
            # worksheet.merge_range('A' + str(start_len + 1) + ':A' + str(excel_row), user_id1, merge_format)
            worksheet.merge_range('A' + str(start_len + 1) + ':A' + str(excel_row), main_sum_time)
            worksheet.merge_range('B' + str(start_len + 1) + ':B' + str(excel_row), main_name)
            worksheet.merge_range('C' + str(start_len + 1) + ':C' + str(excel_row), cover_sum_time)
            worksheet.merge_range('D' + str(start_len + 1) + ':D' + str(excel_row), cover_name)
        i +=1

    # 关闭工作簿
    workbook.close()
    return ajax_ok()

# 网络上传图片/视频到oss
@csrf_exempt
@atomic()
def up_oss_file(request):
    """
    接口功能说明： 上传图片和视频功能
    --------------------------------------------
    接口逻辑说明：
    --------------------------------------------
    修改人        修改时间        修改原因
    --------------------------------------------
    胡庭印        2020-04-20       创建
    --------------------------------------------
    注意事项：后台需要对上传的图片和视频做限制
    """
    if request.method == 'POST':
        files = request.FILES  # 获取文件对象
        '''
         需要通过小程序端的key（image）获取二进制数据
         获取文件内容
        '''
        content = files.get('image', '').read()  # 文件二进制
        content_name = files.get('image', '').name.split('.')[-1].lower()  # 将文件的后缀变小写
        if content_name in ['bmp','jpeg','jpg','png','gif','raw','tif','pcx','tga','exif','fpx','svg','psd','cdr','pcd','dxf','ufo','eps','ai','wmf']:
            file_type = content_name
            file_path = 'images'
        elif content_name in ['xls']:
            file_type = content_name
            file_path = 'excel'
        else:
            ret = {
                'status': 0,  # 格式不支持
            }
            return ajax_ok(data=ret,message='文件格式不支持')

        uuid_name = uuid.uuid1()

        path_files = media_audio(content, file_path, file_type, uuid_name)
        moud_file = os.path.join(path_files, f'{uuid_name}' + '.' + file_type)
        ret_status, Content_MD5, oss_link = upload_oss_file(moud_file, file_path)
        if ret_status == True:
            picture_cover = ''
            li = IMAGES_LINK + oss_link
            print(li,'----------->')
            # if file_path == 'images':
            #     picture_cover = ''
            # elif file_path == 'excel':
            #     picture_cover = li + '?x-oss-process=video/snapshot,t_7000,f_jpg,w_0,h_0,m_fast'
            # ret = {
            #     'status': 1,
            #     'item': li,
            #     'picture_cover': picture_cover
            # }
            data = Struct()
            data.status = 1
            data.item = li
            data.picture_cover = picture_cover
            del_file_one(os.getcwd() + "\\statics\\file\\images\\" + str(li.split('/')[-1]))

            return ajax_ok(data)
        else:
            ret = {
                'status': 0
            }
            return ajax_ok(data=ret)
    return ajax_ok('不成功')


